import { addAccount, getRoleList, updateAccount } from "@/services/permissions/api";
import { showMsg } from "@/utils/utils";
import { ModalForm, ProFormRadio, ProFormSelect, ProFormText } from "@ant-design/pro-form";
import { Card, Col, Row } from "antd";
import { useEffect, useState } from "react";
import { useModel } from "umi";

const SubAdd = (props: SubAddProps) => {

  const { handleModalVisible, finishCallback, editData } = props;
  const oper_id = editData?.oper_id;

  const { initialState } = useModel('@@initialState');
  const { dept_code, dept_name } = initialState?.currentUser || {};

  const [roleList, setRoleList] = useState<COMMON.SelectOption[]>([]);

  useEffect(() => {
    if (dept_code)
      fetchRole(dept_code);
  }, []);

  const fetchRole = (dept_code: string) => {
    getRoleList({ current: 1, pageSize: 99999, dept_code }).then((res: PERMISSIONSAPI.RoleList) => {
      const data = res?.record_list?.map((item) => ({
        label: item.role_name as string,
        value: item.role_id as string,
        dept_code: item.dept_code as string
      }));
      setRoleList(data || []);
    }).catch(err => {
      showMsg(err?.data?.errmsg);
    });
  };

  const onFinish = async (values: PERMISSIONSAPI.AccountListItem) => {
    try {
      if (oper_id) {
        await updateAccount({ ...values, oper_id: editData.oper_id });
      } else {
        await addAccount({ ...values, dept_code, dept_name, dept_level: '2' } as any);
      }
      showMsg('已保存', 'success');
      finishCallback?.();
    } catch (error: any) {
      showMsg(error?.data?.errmsg || (oper_id ? '更新失败' : '添加失败'));
    }
  };

  return (
    <ModalForm<PERMISSIONSAPI.AccountListItem>
      title={`${editData ? '编辑' : '新增'}账户`}
      visible
      initialValues={{ ...editData, status: 'N' }}
      width="60%"
      layout="horizontal"
      className="account-modal-edit"
      modalProps={{ maskClosable: false, destroyOnClose: true }}
      onVisibleChange={handleModalVisible}
      onFinish={onFinish}
    >
      <Card title="1.账号信息" bordered={false} headStyle={{ padding: '0 12px' }} bodyStyle={{ padding: '24px 6px' }}>
        <Row gutter={12}>
          <Col span={8}>
            <ProFormText label="员工姓名" name="oper_name" labelCol={{ flex: '0 0 80px' }} required rules={[{ required: true }]} />
          </Col>
          {
            !editData?.staff_code &&
            <>
              <Col span={8}>
                <ProFormText label="登录手机号" name="mobile" labelCol={{ flex: '0 0 80px' }} required rules={[{ required: true }]} />
              </Col>
              <Col span={8}>
                <ProFormText.Password
                  label="登录密码" name="login_pwd"
                  fieldProps={{ visibilityToggle: true }}
                  labelCol={{ flex: '0 0 80px' }}
                  required={!oper_id} rules={oper_id ? undefined : [{ required: true }]}
                />
              </Col>
            </>
          }
        </Row>
      </Card>
      <Card title="2.角色信息" bordered={false} headStyle={{ padding: '12px 12px 0' }} bodyStyle={{ padding: '24px 6px' }}>
        <ProFormSelect
          rules={[{ required: true }]}
          label="角色分配"
          placeholder="请选择"
          name="role_id"
          labelCol={{ flex: '0 0 80px' }}
          wrapperCol={{ flex: '0 0 calc(100% / 3 - 88px)' }}
          options={roleList as any}
        />
        <ProFormRadio.Group
          rules={[{ required: true, message: '请选择账号状态' }]}
          labelCol={{ flex: '0 0 80px' }}
          label="账号状态"
          name="status"
          options={[
            {
              label: '启用',
              value: 'N'
            },
            {
              label: '停用',
              value: 'S'
            }
          ]}
        />
      </Card>
    </ModalForm>
  );
};

export default SubAdd;

interface SubAddProps {
  handleModalVisible: (visible: boolean) => void
  finishCallback?: () => void
  editData?: PERMISSIONSAPI.AccountListItem
}
